﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace TongueClassLibrary
{
    class AESUtil
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="needEncryptStr">要被加密的字符串</param>
        /// <param name="keyBase64">密钥</param>
        /// <returns>密文base64</returns>
        public static string encrypt(string needEncryptStr, string keyBase64)
        {
            try
            {
                byte[] keyArray = Convert.FromBase64String(keyBase64);
                byte[] toEncryptArray = Encoding.UTF8.GetBytes(needEncryptStr);
                RijndaelManaged rDel = new RijndaelManaged();

                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = rDel.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return Convert.ToBase64String(resultArray, 0, resultArray.Length);

            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="EncryptStr">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文-原密码</returns>
        public static string decrypt(string encryptStr, string keyBase64)
        {
            try
            {
                byte[] keyArray = Convert.FromBase64String(keyBase64);
                byte[] toEncryptArray = Convert.FromBase64String(encryptStr);

                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
